{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. 创建文件列表，通过文件列表创建输入文件队列，读取文件为本章第一节创建的文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "files = tf.train.match_filenames_once(\"Records/output.tfrecords\")\n",
    "filename_queue = tf.train.string_input_producer(files, shuffle=False) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. 解析TFRecord文件里的数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 读取文件。\n",
    "\n",
    "reader = tf.TFRecordReader()\n",
    "_,serialized_example = reader.read(filename_queue)\n",
    "\n",
    "# 解析读取的样例。\n",
    "features = tf.parse_single_example(\n",
    "    serialized_example,\n",
    "    features={\n",
    "        'image_raw':tf.FixedLenFeature([],tf.string),\n",
    "        'pixels':tf.FixedLenFeature([],tf.int64),\n",
    "        'label':tf.FixedLenFeature([],tf.int64)\n",
    "    })\n",
    "\n",
    "decoded_images = tf.decode_raw(features['image_raw'],tf.uint8)\n",
    "retyped_images = tf.cast(decoded_images, tf.float32)\n",
    "labels = tf.cast(features['label'],tf.int32)\n",
    "#pixels = tf.cast(features['pixels'],tf.int32)\n",
    "images = tf.reshape(retyped_images, [784])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. 将文件以100个为一组打包。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "min_after_dequeue = 10000\n",
    "batch_size = 100\n",
    "capacity = min_after_dequeue + 3 * batch_size\n",
    "\n",
    "image_batch, label_batch = tf.train.shuffle_batch([images, labels], \n",
    "                                                    batch_size=batch_size, \n",
    "                                                    capacity=capacity, \n",
    "                                                    min_after_dequeue=min_after_dequeue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5. 训练模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def inference(input_tensor, weights1, biases1, weights2, biases2):\n",
    "        layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)\n",
    "        return tf.matmul(layer1, weights2) + biases2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "After 0 training step(s), loss is 497.954 \n",
      "After 1000 training step(s), loss is 8.30417 \n",
      "After 2000 training step(s), loss is 8.35147 \n",
      "After 3000 training step(s), loss is 8.12348 \n",
      "After 4000 training step(s), loss is 7.99348 \n"
     ]
    }
   ],
   "source": [
    "# 模型相关的参数\n",
    "INPUT_NODE = 784\n",
    "OUTPUT_NODE = 10\n",
    "LAYER1_NODE = 500\n",
    "REGULARAZTION_RATE = 0.0001   \n",
    "TRAINING_STEPS = 5000        \n",
    "\n",
    "weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))\n",
    "biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))\n",
    "\n",
    "weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))\n",
    "biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))\n",
    "\n",
    "y = inference(image_batch, weights1, biases1, weights2, biases2)\n",
    "    \n",
    "# 计算交叉熵及其平均值\n",
    "cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=label_batch)\n",
    "cross_entropy_mean = tf.reduce_mean(cross_entropy)\n",
    "    \n",
    "# 损失函数的计算\n",
    "regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)\n",
    "regularaztion = regularizer(weights1) + regularizer(weights2)\n",
    "loss = cross_entropy_mean + regularaztion\n",
    "\n",
    "# 优化损失函数\n",
    "train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)\n",
    "    \n",
    "# 初始化会话，并开始训练过程。\n",
    "with tf.Session() as sess:\n",
    "    # 由于使用了Coordinator，必须对local和global变量进行初始化\n",
    "    sess.run(tf.local_variables_initializer())\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    coord = tf.train.Coordinator()\n",
    "    threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n",
    "    # 循环的训练神经网络。\n",
    "    for i in range(TRAINING_STEPS):\n",
    "        if i % 1000 == 0:\n",
    "            print(\"After %d training step(s), loss is %g \" % (i, sess.run(loss)))\n",
    "                  \n",
    "        sess.run(train_step) \n",
    "    coord.request_stop()\n",
    "    coord.join(threads)       "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
